package com.sjf.batch.controller;

import com.sjf.batch.mapper.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author <huangtang>
 * @since 2022/1/4 10:43
 **/
@Api(value = "测试Controller")
@RequestMapping("/")
@RestController
public class TestController {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @ApiOperation(value = "获取分布式锁")
    @GetMapping(value = "/redis")
    public String testRedisson () {
        RLock lock = redissonClient.getLock ("lock"); //获取分布式锁

        lock.lock (); //加锁操作
        try {
            System.out.println ("加锁成功，等待1s");
            Thread.sleep (1000);
        } catch (Exception e) {
            System.out.println (e.getMessage ());
        } finally {
            lock.unlock ();
        }
        return "Redisson Lock Success!!";
    }

    @ApiOperation(value = "删除用户")
    @GetMapping(value = "delete")
    public void delete () {
        String[] ids = new String[20];
        for ( int i = 0 ; i < 20 ; i++ ) {
            ids[i] = String.valueOf (i + 1);
        }
        userMapper.delete (ids);
    }

    @ApiOperation(value = "Redis+1")
    @GetMapping(value = "add")
    public String redisAdd () {
        redisTemplate.opsForValue ().increment ("a");
        //redisTemplate.opsForValue().set("a","1");
        //int i = Integer.parseInt((String) redisTemplate.opsForValue().get("a"));
        //redisTemplate.opsForValue().set("a",Integer.toString(i+1));
        return "+1成功";
    }

    @GetMapping(value = "del")
    @ApiOperation(value = "删除Redis中key对应的value")
    public String redisDel (
            @ApiParam(name = "key", value = "key", required = true) String key ) {
        return redisTemplate.delete (key) != null ? "删除成功" : "删除失败";
    }

}
